package com.shqcjd.preinstallmobile.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.DefectManageTypeBean;
import com.shqcjd.preinstallmobile.model.pojo.ProcessBackBean;
import com.shqcjd.preinstallmobile.ui.adapter.ProcessBackAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.Config;
import com.shqcjd.preinstallmobile.util.WrapContentLinearLayoutManager;
import com.shqcjd.preinstallmobile.widget.DateDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * 图像回放
 */
public class ProcessBackActivity extends BaseActivity {
    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.sp_process_back_route)
    Spinner spProcessBackRoute;
    @BindView(R.id.sp_process_back_type)
    Spinner spProcessBackType;
    @BindView(R.id.sp_process_back_state)
    Spinner spProcessBackState;
    @BindView(R.id.rv_process_back)
    RecyclerView rvProcessBack;
    @BindView(R.id.sr_process_back)
    SwipeRefreshLayout srProcessBack;
    @BindView(R.id.btn_process_back_time)
    Button btnProcessBackTime;
    @BindView(R.id.tv_process_back_btime)
    TextView tvProcessBackBtime;
    @BindView(R.id.tv_process_back_etime)
    TextView tvProcessBackEtime;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;


    private Context context;
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private List<ProcessBackBean.ItemsBean> mList = new ArrayList<>();
    private ProcessBackAdapter processBackAdapter;
    private DateDialog dateDialog;

    private String bTime = "";//开始时间
    private String eTime = "";//结束时间
    private int routeId = 0;//巡检路线id 0代表全部路线
    private int typeId = 0;//巡检类型id 1常规巡检 2随机巡检 0全部
    private int stateId = -1;//巡检状态id 0未开始 1进行中 2完成 -1全部

    List<DefectManageTypeBean> rList = new ArrayList<>();
    List routeList = new ArrayList<String>();
    private int total;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_process_back;
    }

    @Override
    public void init() {
        super.init();
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        tvIncludeTitle.setText("图像回放");


        List typeList = new ArrayList<String>();
        typeList.add("巡检类型 ▾");
        typeList.add("全部");
        typeList.add("常规巡检");
        typeList.add("随机巡检");
        ArrayAdapter typeAdapter = new ArrayAdapter<String>(this, R.layout.item_spinner, typeList);
        typeAdapter.setDropDownViewResource(R.layout.item_spinner);
        spProcessBackType.setAdapter(typeAdapter);

        List stateList = new ArrayList<String>();
        stateList.add("巡检状态 ▾");
        stateList.add("全部");
        stateList.add("未开始");
        stateList.add("进行中");
        stateList.add("完成");
        ArrayAdapter stateAdapter = new ArrayAdapter<String>(this, R.layout.item_spinner, stateList);
        stateAdapter.setDropDownViewResource(R.layout.item_spinner);
        spProcessBackState.setAdapter(stateAdapter);

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        srProcessBack.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        btnProcessBackTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dateDialog == null) {
                    dateDialog = new DateDialog(context);
                    dateDialog.setOnCheckDate(new DateDialog.setOnCheckDateListener() {
                        @Override
                        public void onCheckDate(String time, String endTime) {
                            bTime = time;
                            eTime = endTime;
                            tvProcessBackBtime.setText(bTime);
                            tvProcessBackEtime.setText(eTime);
                            refreshData();
                        }
                    });
                }
                dateDialog.show();
            }
        });

        spProcessBackRoute.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0)
                    return;
                if(position==1){
                    routeId=0;
                }else if(position>1){
                    routeId = rList.get(getListValue(routeList.get(position)+"")).value;
                }
                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spProcessBackType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0)
                    return;
                    typeId = position-1;
                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spProcessBackState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0)
                    return;
                if(position==1){
                    stateId = -1;
                }else if(position>1){
                    stateId = position-2;
                }
                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        refreshData();
        getTypeList();
    }

    private void refreshData() {
        refreshOrLoadMore();
        srProcessBack.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        mList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }

    private void refreshOrLoadMore(){
        if(processBackAdapter!=null){
            processBackAdapter.notifyLoadMoreToLoading();
        }
    }

    private void getData(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", p+"");
        map.put("pageSize", Config.PAGE_TOTAL+"");
        map.put("patrol_route_id", routeId+"");//巡检线路id
        map.put("task_type", typeId+"");//巡检类型  1代表常规巡检  2随机巡检
        map.put("task_status", stateId+"");//巡检状态  0未开始  1进行中  2完成 -1全部
        map.put("start_time", bTime);
        map.put("end_time", eTime);
        ApiService.processBackHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ProcessBackBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }
                    
                    @Override
                    public void _onNext(ResponseData<ProcessBackBean> responseData) {
                        if(responseData.retCode!=10000){
                            return;
                        }
                        total = responseData.data.total;
                        mList.addAll(responseData.data.items);
                        if (processBackAdapter == null) {
                            rvProcessBack.setLayoutManager(new WrapContentLinearLayoutManager(context));
                            processBackAdapter = new ProcessBackAdapter(mList,context);
                            rvProcessBack.setAdapter(processBackAdapter);
                            processBackAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                @Override
                                public void onLoadMoreRequested() {
                                    rvProcessBack.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            int pageSize = total%Config.PAGE_TOTAL==0?total/Config.PAGE_TOTAL:total/Config.PAGE_TOTAL+1;
                                            if (page >= pageSize) {
                                                processBackAdapter.loadMoreEnd();
                                            } else {
                                                loadMoreData();
                                            }
                                        }
                                    });
                                }
                            });
                            processBackAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    Intent it = new Intent(context, PlaybackActivity.class);
                                    it.putExtra("tId", mList.get(position).id);
                                    context.startActivity(it);
                                }
                            });
                        }
                        if (isRefreshOrLoadMore == 1) {
                            page = page + 1;
                            processBackAdapter.loadMoreComplete();
                        }
                        if(mList.size()==0){
                            rlIsnull.setVisibility(View.VISIBLE);
                        }else{
                            rlIsnull.setVisibility(View.INVISIBLE);
                        }
                        processBackAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srProcessBack.setRefreshing(false);
                    }
                });
    }

    private void getTypeList() {
        ApiService.playBackTypeHttp()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<DefectManageTypeBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData<List<DefectManageTypeBean>> responseData) {
                        rList = responseData.data;
                        routeList.add("巡检路线 ▾");
                        routeList.add("全部");
                        for(int i=0; i<responseData.data.size(); i++){
                            routeList.add(responseData.data.get(i).label);
                        }
                        ArrayAdapter routeAdapter = new ArrayAdapter<String>(context, R.layout.item_spinner, routeList);
                        routeAdapter.setDropDownViewResource(R.layout.item_spinner);
                        spProcessBackRoute.setAdapter(routeAdapter);

                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private int getListValue(String str){
        for(int i=0; i<rList.size(); i++){
            if(str.equals(rList.get(i).label)){
                return i;
            }
        }
        return 0;
    }
}
